--[[
	function: 设备列表
	author: jim_sun
    wiki: 
    api:
    example:
        curl 'URI/device/get_list?type=xxxxxxxxx&token=xxxxxxx' 
        return
        {
            "status":1,
            "errcode":"",
            "msg":"",
            "data":{
                "list":[...],
                "count":0
            },
        }

]]
local args = ngx.req.get_uri_args()
local token = args.token
local user_id = nil

if not common_util.check_args(1, token) then
    common_util.exit(200, 0, nil, "101", "token is missing")
end

local user_id = common_util.get_user_id_by_token(token)
if not user_id then
    common_util.exit(200, 0, nil, "105", "token is ....")
end

local get_gate_way_list_func = function()
    local sql = "select gateway_name,gateway_id from tb_gateway_info where status=1 and user_id="..user_id
    local data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
    if false == bool  then
        --connection:over()
        common_util.exit(200, 0, nil, "500", "mysql is error")
    end
    if next(data) then
        return data
    end
    return nil
end

local get_device_list_func = function()
    local sql = "select b.device_name,b.device_id,b.gateway_id,b.device_type from tb_user_device_info a inner join tb_device_common_info b ON a.user_id="
        ..user_id.." and a.gateway_id=b.gateway_id and a.device_id=b.device_id and a.status=1"
    local data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
    if false == bool  then
        --connection:over()
        common_util.exit(200, 0, nil, "500", "mysql is error")
    end
    if next(data) then
        return data
    end
    return nil
end

local method = {
    ["device"] = get_device_list_func, --获取设备列表
    ["gate_way"] = get_gate_way_list_func, --获取网关列表
}

if not method[args.type] then
    common_util.exit(200, 0, nil, "101", "type is missing")
end
local list = method[args.type]() or {}
setmetatable(list, cjson.empty_array_mt)
common_util.exit(200, 1, {["list"] = list, count = #list}, "", "success")



